import '../../public.dart';
import './model.dart';
import './image_upload_widget.dart';
import 'form_validator.dart';
import 'package:intl/intl.dart';

class SellGiftCardDetailPage extends StatelessWidget {
  final int cardTypeId;
  final String cardTypeName;
  final SysGiftCardCategoryEntity? category;

  const SellGiftCardDetailPage({
    super.key,
    required this.cardTypeId,
    required this.cardTypeName,
    this.category,
  });

  @override
  Widget build(BuildContext context) {
    return ProviderWidget<SellGiftCardDetailModel>(
      model: SellGiftCardDetailModel(
        cardTypeId: cardTypeId,
        cardTypeName: cardTypeName,
        defaultCategory: category,
      ),
      onModelReady: (model) {
        model.init();
      },
      builder: (context, model, child) {
        return _SellGiftCardDetailContent();
      },
    );
  }
}

class _SellGiftCardDetailContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<SellGiftCardDetailModel>(context);

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        title: Text(provider.cardTypeName),
        centerTitle: true,
        elevation: 0,
      ),
      body: SafeArea(
        child: Stack(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 子类别选择
                  _buildSubcategorySection(context, provider),
                  const SizedBox(height: 16),

                  // 汇率和最低金额信息
                  _buildRateInfoSection(provider),
                  const SizedBox(height: 16),

                  // 卡金额输入
                  _buildAmountInputSection(context, provider),
                  const SizedBox(height: 16),

                  // 现金价值显示
                  _buildCashValueSection(context, provider),
                  const SizedBox(height: 24),

                  // 上传图片区域
                  _buildImageUploadSection(context, provider),
                  const SizedBox(height: 24),

                  // 卡号输入
                  _buildCodeInputSection(context, provider),
                  const SizedBox(height: 32),

                  // 确认按钮
                  _buildConfirmButton(context, provider),
                  const SizedBox(height: 32),
                ],
              ),
            ),
            // 加载指示器
            if (provider.isLoading)
              const Positioned.fill(
                child: Center(child: CircularProgressIndicator()),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildSubcategorySection(
    BuildContext context,
    SellGiftCardDetailModel provider,
  ) {
    // 在加载子类别时禁用选择器
    final isEnabled = !provider.isLoadingSubcategories;

    return CommonSelector(
      label: 'Sub-category',
      placeholder: 'Select option',
      value: provider.selectedSubcategory,

      onTap: isEnabled
          ? () => showSubcategoryOptions(context, provider)
          : () {},
      enabled: isEnabled, // 根据加载状态控制是否启用
    );
  }

  Widget _buildRateInfoSection(SellGiftCardDetailModel provider) {
    // 获取选中子类别的最小额度
    final minimum = provider.selectedSubcategoryEntity?.minimum;
    // 获取API返回的汇率
    final rate = provider.exchangeRate?.toInt() ?? "";

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        // Rate 显示（蓝色）
        RichText(
          text: TextSpan(
            children: [
              const TextSpan(
                text: 'Rate: ',
                style: TextStyle(fontSize: 14, color: Colors.black87),
              ),
              TextSpan(
                text: rate.toString(),
                style: const TextStyle(
                  fontSize: 14,
                  color: Color(0xFF2196F3), // 蓝色
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        ),
        // Minimum 显示（橙色）
        RichText(
          text: TextSpan(
            children: [
              const TextSpan(
                text: 'Minimum: ',
                style: TextStyle(fontSize: 14, color: Colors.black87),
              ),
              TextSpan(
                text: minimum?.toString() ?? "",
                style: const TextStyle(
                  fontSize: 14,
                  color: Color(0xFF2196F3),
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildAmountInputSection(
    BuildContext context,
    SellGiftCardDetailModel provider,
  ) {
    final minimum = provider.selectedSubcategoryEntity?.minimum;
    final minimumText = (minimum != null && minimum > 0)
        ? minimum.toString()
        : "--";

    return CommonFormField(
      label: 'Amount on card',
      hintText: 'Enter amount (minimum: $minimumText)',
      onChanged: provider.setCardAmount,
      keyboardType: TextInputType.number,
      validator: (value) => provider.validateAmount(), // Flutter会自动在输入框下方显示错误
      errorText: provider.currentValidationError, // 传递验证错误
    );
  }

  Widget _buildCashValueSection(
    BuildContext context,
    SellGiftCardDetailModel provider,
  ) {
    // 使用NumberFormat实现千分符格式化
    final formattedCashValue = FmtUtil.formatBalanceWithThousandSeparators(
      provider.cashValue.toString(),
    );

    return Column(
      children: [
        const Center(
          child: Text(
            'Cash value',
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
          ),
        ),
        Center(
          child: Text(
            '₦ $formattedCashValue',
            style: const TextStyle(
              fontSize: 48,
              fontWeight: FontWeight.bold,
              color: Color(0xFF4CAF50),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildImageUploadSection(
    BuildContext context,
    SellGiftCardDetailModel provider,
  ) {
    return ImageUploadWidget(
      images: provider.uploadedImages,
      onImageAdded: provider.addImage,
      onImageRemoved: provider.removeImage,
      maxImages: 9,
    );
  }

  Widget _buildCodeInputSection(
    BuildContext context,
    SellGiftCardDetailModel provider,
  ) {
    return CommonFormField(
      label: 'Add Code(s)',
      hintText: 'Enter code number',
      onChanged: provider.setCardCode,
    );
  }

  Widget _buildConfirmButton(
    BuildContext context,
    SellGiftCardDetailModel provider,
  ) {
    return SizedBox(
      width: double.infinity,
      child: ElevatedButton(
        onPressed: () => onConfirm(context, provider),
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFF4CAF50),
          padding: const EdgeInsets.symmetric(vertical: 16),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
        ),
        child: const Text(
          'Confirm',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
        ),
      ),
    );
  }

  void showSubcategoryOptions(
    BuildContext context,
    SellGiftCardDetailModel provider,
  ) {
    // 如果正在加载子类别，直接返回并显示加载状态
    if (provider.isLoadingSubcategories) {
      Toast.show('Loading subcategories...');
      return;
    }

    // 显示子类别选项
    showModalBottomSheet(
      context: context,
      isScrollControlled: true, // 允许底部表单完全控制滚动
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16.0),
          topRight: Radius.circular(16.0),
        ),
      ),
      backgroundColor: Colors.white,
      builder: (context) {
        // 如果正在加载子类别，显示加载状态
        if (provider.isLoadingSubcategories) {
          return Container(
            height: 100,
            padding: const EdgeInsets.all(16.0),
            child: const Center(child: CircularProgressIndicator()),
          );
        }

        // 过滤出有效的子类别选项
        final validCategories = provider.subcategories
            .where(
              (category) =>
                  category.categoryName != null &&
                  category.categoryName!.isNotEmpty,
            )
            .toList();

        return Container(
          padding: const EdgeInsets.all(16.0),
          constraints: BoxConstraints(
            minWidth: MediaQuery.of(context).size.width,
            maxHeight:
                MediaQuery.of(context).size.height * 0.7, // 限制最大高度为屏幕的70%
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 添加一个指示器
              Container(
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(2),
                  color: Colors.grey.shade300,
                ),
                margin: const EdgeInsets.only(bottom: 16.0),
              ),
              const Text(
                'Select Subcategory',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),
              // 添加滚动视图以支持大量选项
              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.only(bottom: 16.0),
                  physics: const BouncingScrollPhysics(), // 添加弹性滚动效果
                  child: Column(
                    children: [
                      // 从API获取的子类别列表
                      if (validCategories.isEmpty)
                        const Padding(
                          padding: EdgeInsets.all(24.0),
                          child: Text(
                            'No subcategories available',
                            textAlign: TextAlign.center,
                            style: TextStyle(color: Colors.grey),
                          ),
                        )
                      else
                        ...validCategories.map(
                          (category) => buildSubcategoryOption(
                            context,
                            provider,
                            category.categoryName ?? '',
                            category.id,
                          ),
                        ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget buildSubcategoryOption(
    BuildContext context,
    SellGiftCardDetailModel provider,
    String option,
    int? categoryId,
  ) {
    // 检查当前选项是否被选中
    bool isSelected = provider.selectedSubcategory == option;

    return InkWell(
      onTap: () {
        provider.setSubcategory(option, categoryId: categoryId);
        Navigator.pop(context);
      },
      splashColor: Colors.grey.shade200, // 添加点击水波纹效果
      highlightColor: Colors.grey.shade100,
      child: Container(
        width: double.infinity, // 确保宽度占满
        padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 16),
        decoration: BoxDecoration(
          border: const Border(
            bottom: BorderSide(color: Color(0xFFEEEEEE), width: 0.5),
          ),
          // 添加选中状态的背景色
          color: isSelected ? Colors.grey.shade50 : Colors.transparent,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: Text(
                option,
                style: TextStyle(
                  fontSize: 15, // 稍微减小字体大小以适应更多内容
                  color: isSelected ? const Color(0xFF4CAF50) : Colors.black87,
                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            // 如果选中，显示勾选图标
            if (isSelected)
              const Icon(
                Icons.check_circle,
                color: Color(0xFF4CAF50),
                size: 20,
              ),
          ],
        ),
      ),
    );
  }

  void onConfirm(BuildContext context, SellGiftCardDetailModel provider) {
    // 确认按钮点击处理
    if (provider.validateForm()) {
      // 提交表单数据
      submitForm(context, provider);
    } else {
      // 显示验证错误，按优先级顺序检查
      final subcategoryError = FormValidator.validateSubcategory(
        provider.selectedSubcategory,
      );
      if (subcategoryError != null) {
        Toast.show(subcategoryError);
        return;
      }

      final amountError = provider.validateAmount();
      if (amountError != null) {
        Toast.show(amountError);
        return;
      }

      final imageError = FormValidator.validateImages(provider.uploadedImages);
      if (imageError != null) {
        Toast.show(imageError);
        return;
      }

      final codeError = FormValidator.validateRequired(
        provider.cardCode,
        'card code',
      );
      if (codeError != null) {
        Toast.show(codeError);
        return;
      }
    }
  }

  void submitForm(
    BuildContext context,
    SellGiftCardDetailModel provider,
  ) async {
    // 创建局部变量来存储上下文，避免在异步操作中使用可能失效的上下文
    final localContext = context;
    provider.setLoading(true);
    try {
      // TODO: 实现表单提交逻辑
      debugPrint('Submitting form...');
      await provider.submitSellCard(context); // 模拟网络请求
      // 使用局部上下文
      if (localContext.mounted) {
        Toast.show('Card submitted successfully');
        Navigator.pop(localContext);
      }
    } catch (e) {
      debugPrint('Failed to submit card: $e');
      // 即使出错也使用局部上下文
      if (localContext.mounted) {
        Toast.show('Failed to submit card, please try again');
      }
    } finally {
      provider.setLoading(false);
    }
  }
}
